import dayjs from 'dayjs'
import config from '@/config/index'

// 公共format
export const format = (D: string | number | Date, type = config.dateTimeFormat) => {
  return dayjs(D).format(type)
}

// 评论时间（时间不可以在未来）
export const getMixtureDate = (D?: string | number | Date, format = 'MM-DD') => {
  if (!D) return ''
  const date = dayjs(D)
  const now = dayjs()
  if (date.valueOf() - now.valueOf() > 0) return ''

  const diffM = now.diff(date, 'minute')
  const diffH = now.diff(date, 'hour')

  if (diffM < 15) {
    return '刚刚'
  } else if (diffM >= 15 && diffM < 60) {
    // 5-59分钟之间
    return `${diffM}分钟前`
  } else if (diffM >= 60 && diffH < 24) {
    // 1-23小时之间
    return `${diffM}小时前`
  } else if (diffH >= 24) {
    return date.format(format)
  }
  return ''
}

// 中文时长
export const getZhTime = (ms: number) => {
  if (!ms) return ''

  const s = Math.floor(ms / 1000)
  if (s < 1) {
    return `${ms}毫秒`
  } else if (s >= 1 && s <= 60) {
    return `${s}秒`
  } else if (s > 60 && s <= 60 * 60) {
    const M = Math.floor(s / 60)
    const S = s % 60
    return M + '分钟' + (S ? S + '秒' : '')
  } else {
    const H = Math.floor(s / (60 * 60))
    const M = Math.floor((s % (60 * 60)) / 60)
    const S = s % 60
    return H + '小时' + (M ? M + '分钟' : '') + (S ? S + '秒' : '')
  }
}

// 倒计时
export const countDown = (options: {
  date: number | string | Date
  closeTime?: number
  callback: (str: string) => void
  onCloseToFinish?: () => void
  onFinish?: () => void
}) => {
  const {
    date, // 结束时间戳（时间不可以在过去）
    closeTime = 60 * 60 * 1000, // 临近结束（默认1小时，0为不设限）
    callback, // 每秒返回一次当前时间
    onCloseToFinish, // 临近结束时触发
    onFinish // 结束时触发
  } = options || {}
  const D = dayjs(date)
  let onCloseToFinishLock = 0 // 临近结束锁，仅一次

  // 执行
  const payTimer = setInterval(down, 1000)
  down()

  function addZero(num: number) {
    return num < 10 ? '0' + num : num
  }
  function down() {
    const now = dayjs()
    const lastTime = D.valueOf() - now.valueOf() // 剩余时间（毫秒）
    if (lastTime < 0) {
      onFinish?.()
      clearInterval(payTimer)
      return
    }

    const hours = D.diff(now, 'hour')
    const minutes = D.diff(now, 'minute') % 60
    const seconds = D.diff(now, 'second') % 60

    let text = '' // 时间文案
    if (closeTime !== 0 && lastTime > closeTime) {
      const h = hours > 0 ? `${hours}小时` : ''
      text = `${h}${minutes}分钟`
    } else {
      text = `${addZero(hours)}:${addZero(minutes)}:${addZero(seconds)}`
      if (onCloseToFinishLock === 0) onCloseToFinish?.()
      onCloseToFinishLock = 1
    }
    callback?.(text) // 每秒返回一次
    if (hours <= 0 && minutes <= 0 && seconds <= 0) {
      onFinish?.()
      clearInterval(payTimer)
    }
  }
}

export default {
  format,
  getMixtureDate,
  getZhTime,
  countDown
}
